package com.lingkang.flychat.controller;

import com.lingkang.flychat.domain.FcUser;
import com.lingkang.flychat.dto.ResponseResult;
import com.lingkang.flychat.mapper.FcUserMapper;
import com.lingkang.flychat.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

/**
 * @author linke
 * @date 2020/3/28 23:35
 * @description
 */
@Controller
public class LoginController {

    @Autowired
    private FcUserMapper fcUserMapper;
    @Autowired
    private RedisService redisService;

    @PostMapping("/login")
    @ResponseBody
    public ResponseResult info(String username, String password) {
        if (StringUtils.isEmpty(username))
            return new ResponseResult(1, "账号不能为空");
        if (StringUtils.isEmpty(password))
            return new ResponseResult<>(1, "密码不能为空");
        FcUser fcUser = fcUserMapper.getInfo(username);
        if (fcUser == null)
            return new ResponseResult(1, "账号不存在");
        if (!fcUser.getPassword().equals(password))
            return new ResponseResult<>(1, "密码错误");
        Object t = redisService.get(String.format("u_t:%s", username));
        if (t != null) {
            return new ResponseResult(0, "登录成功", t.toString());
        }
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisService.set(String.format("u_t:%s", username), token, 60 * 60 * 24 * 15);
        redisService.set(String.format("token:%s", token), fcUser.getUsername(), 60 * 60 * 24 * 15);
        return new ResponseResult(0, "登录成功", token);
    }
}
